import { createRouter, createWebHashHistory } from "vue-router";
import { routes } from "./routes";
import { useUserStore } from "../store/user";
import { useOrdersStore } from "../store/order";

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 挂载路由导航守卫：to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const orderStore = useOrdersStore();
  // 修改页面 title
  if (to.meta.title) {
    document.title = "小米售后工单履约系统 - " + to.meta.title;
  }
  // 放行登录页面
  if (to.path === "/user/login"|| to.path === "/user/register") {
    sessionStorage.removeItem("user");
    next();
    return;
  }
  if (sessionStorage.getItem("user") != null && sessionStorage.getItem("user") != "undefined") {
    userStore.actions.setLoginUser(JSON.parse(sessionStorage.getItem("user")));
  }
  if (sessionStorage.getItem("order") != null && sessionStorage.getItem("order") != "undefined") {
    orderStore.actions.setOrderList(JSON.parse(sessionStorage.getItem("order")));
  }
  const userName = userStore.state.name;
  if (userName === "未登录") {
    next("/user/login");
    return;
  } else {
    next();
    return;
  }
});

// 导出路由
export default router;
